package com.ss.android.download;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public final class k {
    final static class a extends SQLiteOpenHelper {
        public a(Context arg4) {
            super(arg4, "ss_downloads.db", null, 100);
        }

        private static void a(SQLiteDatabase arg3, ContentValues arg4) {
            arg3.update("ss_downloads", arg4, arg4.valueSet().iterator().next().getKey() + " is null", null);
            arg4.clear();
        }

        public final void onCreate(SQLiteDatabase arg3) {
            if (com.ss.android.download.aa.d) {
                Log.v("SsDownloadManager", "populating new database");
            }

            this.onUpgrade(arg3, 0, 100);
        }

        public final void onUpgrade(SQLiteDatabase arg6, int arg7, int arg8) {
            int v0 = 99;
            if (arg7 < 100) {
                Log.i("SsDownloadManager", "Upgrading downloads database from version " + arg7 + " to version " + arg8 + ", which will destroy all old data");
                arg7 = v0;
            } else if (arg7 > arg8) {
                Log.i("SsDownloadManager", "Downgrading downloads database from version " + arg7 + " (current version is " + arg8 + "), destroying all old data");
                arg7 = v0;
            }

            try {
                v0 = arg7 + 1;
                while (true) {
                    label_17:
                    if (v0 > arg8) {
                        return;
                    }

                    switch (v0) {
                        case 100:
                            break;
                        default:
                            throw new IllegalStateException("Don\'t know how to upgrade to " + v0);
                    }

                    try {
                        label_57:
                        arg6.execSQL("DROP TABLE IF EXISTS ss_downloads");
                        arg6.execSQL("CREATE TABLE ss_downloads(_id INTEGER PRIMARY KEY AUTOINCREMENT,uri TEXT, entity TEXT, no_integrity BOOLEAN, hint TEXT, _data TEXT, mimetype TEXT, destination INTEGER, visibility INTEGER, control INTEGER, status INTEGER, numfailed INTEGER, lastmod BIGINT, notificationpackage TEXT, notificationextras TEXT, cookiedata TEXT, useragent TEXT, referer TEXT, total_bytes INTEGER, current_bytes INTEGER, title TEXT, description TEXT, allow_roaming INTEGER NOT NULL DEFAULT 0, allowed_network_types INTEGER NOT NULL DEFAULT 0, is_visible_in_downloads_ui INTEGER NOT NULL DEFAULT 1, bypass_recommended_size_limit INTEGER NOT NULL DEFAULT 0, mediaprovider_uri TEXT, deleted BOOLEAN NOT NULL DEFAULT 0, errorMsg TEXT, allow_write BOOLEAN NOT NULL DEFAULT 0, etag TEXT, scanned INTEGER, method INTEGER);");
                    } catch (SQLException v0_2) {
                        Log.e("SsDownloadManager", "couldn\'t create table in downloads database");
                        throw v0_2;
                    }

                    arg6.execSQL("DROP TABLE IF EXISTS request_headers");
                    arg6.execSQL("CREATE TABLE request_headers(id INTEGER PRIMARY KEY AUTOINCREMENT,download_id INTEGER NOT NULL,header TEXT NOT NULL,value TEXT NOT NULL);");
                    ContentValues v1 = new ContentValues();
                    v1.put("is_visible_in_downloads_ui", Boolean.valueOf(false));
                    arg6.update("ss_downloads", v1, "destination != 0", null);
                    v1 = new

                            ContentValues();
                    v1.put("current_bytes", Integer.valueOf(0));
                    a(arg6, v1);
                    v1.put("total_bytes", Integer.valueOf(-1));
                    a(arg6, v1);
                    v1.put("title", "");
                    a(arg6, v1);
                    v1.put("description", "");
                    a(arg6, v1);
                    ++v0;
                    continue;
                }
            } catch (Exception e) {
                Log.i("SsDownloadManager", "onUpgrade " + arg7 + " to " + arg8 + " exception: " + e);
            }

        }
    }

    static final class b {
        public StringBuilder a;
        private List b;

        b(byte arg1) {
            this();
        }

        private b() {

            this.a = new StringBuilder();
            this.b = new ArrayList();
        }

        public final void a(String arg5, Object[] arg6) {
            if (arg5 != null && !TextUtils.isEmpty(((CharSequence) arg5))) {
                if (this.a.length() != 0) {
                    this.a.append(" AND ");
                }

                this.a.append("(");
                this.a.append(arg5);
                this.a.append(")");
                if (arg6 == null) {
                    return;
                }

                int v1 = arg6.length;
                int v0;
                for (v0 = 0; v0 < v1; ++v0) {
                    this.b.add(arg6[v0].toString());
                }
            }
        }

        public final String[] a() {
            return (String[]) this.b.toArray(new String[this.b.size()]);
        }
    }

    private static final UriMatcher a;
    private static final Uri[] b;
    private static final HashMap c;
    private SQLiteOpenHelper d;
    private static final Object e;
    private static k f;
    private t g;
    private Context h;

    static {
        UriMatcher v0 = new UriMatcher(-1);
        a = v0;
        a.addURI("com.ss.android.newmedia.downloads", "all_downloads", 1);
        a.addURI("com.ss.android.newmedia.downloads", "all_downloads/#", 2);
        a.addURI("com.ss.android.newmedia.downloads", "all_downloads/#/headers", 3);
        a.addURI("com.ss.android.newmedia.downloads", "download/#/headers", 3);
        b = new Uri[]{com.ss.android.download.a.a.a};
        HashMap v0_1 = new HashMap();
        c = v0_1;
        v0_1.put("_display_name", "title AS _display_name");
        k.c.put("_size", "total_bytes AS _size");
        e = new Object();
    }

    private k(Context arg3) {

        this.d = null;
        this.h = arg3;
        if (this.g == null) {
            this.g = p.a(arg3);
        }

        this.d = new a(arg3);
        try {
            arg3.startService(new Intent(arg3, DownloadService.class));
        } catch (Exception v0) {
        }
    }

    public final Cursor a(Uri arg10, String[] arg11, String arg12, String[] arg13, String arg14) {
        Cursor v0_2;
        Cursor v8 = null;
        try {
            SQLiteDatabase v0_1 = this.d.getReadableDatabase();
            int v1 = k.a.match(arg10);
            if (v1 == -1) {
                if (com.ss.android.download.aa.c) {
                    Log.v("SsDownloadManager", "querying unknown URI: " + arg10);
                }

                throw new IllegalArgumentException("Unknown URI: " + arg10);
            }

            if (v1 == 3) {
                if (arg11 != null || arg12 != null || arg14 != null) {
                    throw new UnsupportedOperationException("Request header queries do not support projections, selections or sorting");
                }

                v0_2 = v0_1.query("request_headers", new String[]{"header", "value"}, "download_id=" + k.b(arg10), null, null, null, null);
                return v0_2;
            }

            b v2 = k.a(arg10, arg12, arg13, v1);
            if (com.ss.android.download.aa.d) {
                k.a(arg11, arg12, arg13, arg14, v0_1);
            }

            v0_2 = v0_1.query("ss_downloads", arg11, v2.a.toString(), v2.a(), null, null, arg14);
            if (v0_2 != null) {
                v0_2.setNotificationUri(this.h.getContentResolver(), arg10);
                if (!com.ss.android.download.aa.d) {
                    return v0_2;
                }

                Log.v("SsDownloadManager", "created cursor " + v0_2 + " on behalf of " + Binder.getCallingPid());
                return v0_2;
            }

            if (!com.ss.android.download.aa.c) {
            } else {
                Log.v("SsDownloadManager", "query failed in downloads database");
                return v0_2;
            }

            return v0_2;
        } catch (Exception v0) {
            return v8;
        }
    }

    public static k a(Context arg3) {
        Object v1 = k.e;
        synchronized (v1) {
            if (k.f == null) {
                k.f = new k(arg3.getApplicationContext());
            }
        }

        return k.f;
    }

    public final int a(Uri arg11, ContentValues arg12, String arg13, String[] arg14) {
        Context v1_4;
        int v2;
        int v0_4;
        Cursor v0_2 = null;
        String v9;
        int v7;
        SQLiteDatabase v8;
        try {
            v8 = this.d.getWritableDatabase();
            v7 = 0;
            if ((arg12.containsKey("deleted")) && arg12.getAsInteger("deleted").intValue() == 1) {
                v7 = 1;
            }
            v9 = arg12.getAsString("_data");
            if (v9 == null) {
            } else {
                try {
                    v0_2 = this.a(arg11, new String[]{"title"}, null, null, null);
                    if (!v0_2.moveToFirst() || (TextUtils.isEmpty(v0_2.getString(0)))) {
                        arg12.put("title", new File(v9).getName());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (v0_2 != null) {
                        try {
                            v0_2.close();
                        } catch (Exception e) {

                        }
                    }
                }
            }

            Integer v0_3 = arg12.getAsInteger("status");
            if (v0_3 != null) {
                if (v0_3.intValue() != 190 && v0_3.intValue() != 201 && v0_3.intValue() != 193) {
                    v0_4 = 0;
                } else {
                    v0_4 = 1;
                }
            } else {
                v0_4 = 0;
            }

            boolean v1_2 = arg12.containsKey("bypass_recommended_size_limit");
            int v1_3;
            if (v0_4 != 0) {
                v1_3 = 1;
            } else if (!v1_2) {
                v1_3 = v7;
            } else {
                v1_3 = 1;
            }
            v1_3 = 1;
            label_59:
            v2 = k.a.match(arg11);
            switch (v2) {
                case 1:
                case 2: {
                    break;
                }
                default:
                    Log.d("SsDownloadManager", "updating unknown/invalid URI: " + arg11);
                    throw new UnsupportedOperationException("Cannot update URI: " + arg11);
            }


            b v0_5 = k.a(arg11, arg13, arg14, v2);
            if (arg12.size() > 0) {
                v0_4 = v8.update("ss_downloads", arg12, v0_5.a.toString(), v0_5.a());
            } else {
                v0_4 = 0;
            }

            this.a(arg11, v2);
            if (v1_3 == 0) {
                return v0_4;
            }

            v1_4 = this.h;
        } catch (Exception v0) {
            return 0;
        }

        try {
            v1_4.startService(new Intent(v1_4, DownloadService.class));
        } catch (Exception v1_1) {
        }

        return v0_4;
    }

    public final int a(Uri arg13) {
        Cursor v1 = null;
        b v11;
        int v10;
        SQLiteDatabase v0_1;
        try {
            v0_1 = this.d.getWritableDatabase();
            v10 = k.a.match(arg13);
            switch (v10) {
                case 1:
                case 2:
                    v11 = k.a(arg13, null, null, v10);
                    v1 = v0_1.query("ss_downloads", new String[]{"_id"}, v11.a.toString(), v11.a(), null, null, null, null);
                    break;
                default:
                    Log.d("SsDownloadManager", "deleting unknown/invalid URI: " + arg13);
                    throw new UnsupportedOperationException("Cannot delete URI: " + arg13);
            }


            v1.moveToFirst();
            while (!v1.isAfterLast()) {
                v0_1.delete("request_headers", "download_id=" + v1.getLong(0), null);
                v1.moveToNext();
            }
            int v0_3 = v0_1.delete("ss_downloads", v11.a.toString(), v11.a());
            this.a(arg13, v10);
            return v0_3;
        } catch (Throwable v0_2) {
            return 0;
        } finally {
            try {
                v1.close();
            } catch (Exception v1_1) {
            }
        }
    }

    public final Uri a(Uri arg13, ContentValues arg14) {
        Context v0_5;
        long v2_1;
        Iterator v2;
        StringBuilder v1_1;
        Uri v1 = null;
        this.h.enforceCallingOrSelfPermission("android.permission.INTERNET", "INTERNET permission is required to use the download manager");
        ContentValues v4 = new ContentValues(arg14);
        k.a(v4, "destination", new Object[]{Integer.valueOf(1)});
        k.a(v4, "visibility", new Object[]{Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(3), Integer.valueOf(2)});
        v4.remove("uri");
        v4.remove("title");
        v4.remove("description");
        v4.remove("mimetype");
        v4.remove("hint");
        v4.remove("notificationpackage");
        v4.remove("allowed_network_types");
        v4.remove("allow_roaming");
        v4.remove("is_visible_in_downloads_ui");
        v4.remove("scanned");
        v4.remove("allow_write");
        Iterator v5 = v4.valueSet().iterator();
        while (v5.hasNext()) {
            Map.Entry entry = (Map.Entry) v5.next();
            if (!((String) entry.getKey()).startsWith("http_header_")) {
                continue;
            }

            v5.remove();
        }

        if (v4.size() > 0) {
            v1_1 = new StringBuilder("Invalid columns in request: ");
            v2 = v4.valueSet().iterator();
        } else {
            try {
                SQLiteDatabase v4_1 = this.d.getWritableDatabase();
                int v5_1 = k.a.match(arg13);
                if (v5_1 != 1) {
                    Log.d("SsDownloadManager", "calling insert on an unknown/invalid URI: " + arg13);
                    throw new IllegalArgumentException("Unknown/Invalid URI " + arg13);
                }

                ContentValues v6 = new ContentValues();
                k.c("uri", arg14, v6);
                k.c("entity", arg14, v6);
                k.b("no_integrity", arg14, v6);
                k.c("hint", arg14, v6);
                k.c("mimetype", arg14, v6);
                Integer v0_1 = arg14.getAsInteger("destination");
                if (v0_1 != null) {
                    if (v0_1.intValue() == 1) {
                        this.h.enforcePermission("android.permission.WRITE_EXTERNAL_STORAGE", Binder.getCallingPid(), Binder.getCallingUid(), "need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI");
                        String v7 = arg14.getAsString("hint");
                        if (v7 == null) {
                            throw new IllegalArgumentException("DESTINATION_FILE_URI must include a file URI under COLUMN_FILE_NAME_HINT");
                        } else {
                            Uri v7_1 = Uri.parse(v7);
                            String v8 = v7_1.getScheme();
                            if (v8 != null && (v8.equals("file"))) {
                                v8 = v7_1.getPath();
                                if (v8 == null) {
                                    throw new IllegalArgumentException("Invalid file URI: " + v7_1);
                                } else {
                                    try {
                                        if (!new File(v8).getCanonicalPath().startsWith(Environment.getExternalStorageDirectory().getAbsolutePath())) {
                                            throw new SecurityException("Destination must be on external storage: " + v7_1);
                                        }
                                    } catch (IOException v0_2) {
                                        throw new SecurityException("Problem resolving path: " + v7_1);
                                    }
                                }
                            } else {
                                throw new IllegalArgumentException("Not a file URI: " + v7_1);
                            }
                        }
                    }
                    v6.put("destination", v0_1);
                }
                Integer v7_2 = arg14.getAsInteger("visibility");
                if (v7_2 != null) {
                    v6.put("visibility", v7_2);
                } else if (v0_1.intValue() == 0) {
                    v6.put("visibility", Integer.valueOf(1));
                } else {
                    v6.put("visibility", Integer.valueOf(2));
                }

                k.a("control", arg14, v6);
                v6.put("status", Integer.valueOf(190));
                v6.put("total_bytes", Integer.valueOf(-1));
                v6.put("current_bytes", Integer.valueOf(0));
                v6.put("lastmod", Long.valueOf(this.g.a()));
                String v7 = arg14.getAsString("notificationpackage");
                if (v7 != null) {
                    v6.put("notificationpackage", v7);
                }
                k.c("notificationextras", arg14, v6);
                k.c("cookiedata", arg14, v6);
                k.c("useragent", arg14, v6);
                k.c("referer", arg14, v6);
                k.a("title", arg14, v6, "");
                k.a("description", arg14, v6, "");
                if (arg14.containsKey("is_visible_in_downloads_ui")) {
                    k.b("is_visible_in_downloads_ui", arg14, v6);
                } else {
                    boolean v0_3 = v0_1 == null || v0_1.intValue() == 0 ? true : false;
                    v6.put("is_visible_in_downloads_ui", Boolean.valueOf(v0_3));
                }
                k.a("allowed_network_types", arg14, v6);
                k.b("allow_roaming", arg14, v6);
                v2_1 = v4_1.insert("ss_downloads", null, v6);
                if (v2_1 == -1) {
                    Log.d("SsDownloadManager", "couldn\'t insert into downloads database");
                    Uri v0_4 = v1;
                    return v0_4;
                }
                k.a(v4_1, v2_1, arg14);
                this.a(arg13, v5_1);
                v0_5 = this.h;
                v0_5.startService(new Intent(v0_5, DownloadService.class));
                return ContentUris.withAppendedId(com.ss.android.download.a.a.a, v2_1);
            } catch (Exception v0) {
                return v1;
            }
        }

        while (v2.hasNext()) {
            Map.Entry entry = (Map.Entry) v2.next();
            v1_1.append(entry.getKey());
        }
        throw new SecurityException(v1_1.toString());
    }

    private static b a(Uri arg5, String arg6, String[] arg7, int arg8) {
        b v0 = new com.ss.android.download.k.b((byte) 0);
        v0.a(arg6, ((Object[]) arg7));
        if (arg8 == 2) {
            v0.a("_id = ?", new String[]{k.b(arg5)});
        }

        return v0;
    }

    private static void a(ContentValues arg4, String arg5, Object[] arg6) {
        Object v1 = arg4.get(arg5);
        arg4.remove(arg5);
        int v2 = arg6.length;
        int v0;
        for (v0 = 0; v0 < v2; ++v0) {
            Object v3 = arg6[v0];
            if (v1 == null && v3 == null || v1 != null && (v1.equals(v3))) {
                return;
            }
        }

        throw new SecurityException("Invalid value for " + arg5 + ": " + v1);
    }

    private static void a(SQLiteDatabase arg5, long arg6, ContentValues arg8) {
        ContentValues v2 = new ContentValues();
        v2.put("download_id", Long.valueOf(arg6));
        Iterator v3 = arg8.valueSet().iterator();
        while (v3.hasNext()) {
            Object v0 = v3.next();
            String key = (String) ((Map.Entry) v0).getKey();
            if (!key.startsWith("http_header_")) {
                continue;
            }

            String v0_1 = ((Map.Entry) v0).getValue().toString();
            if (!v0_1.contains(":")) {
                throw new IllegalArgumentException("Invalid HTTP header line: " + v0_1);
            }

            String[] v0_2 = v0_1.split(":", 2);
            v2.put("header", v0_2[0].trim());
            v2.put("value", v0_2[1].trim());
            arg5.insert("request_headers", null, v2);
        }
    }

    private void a(Uri arg9, int arg10) {
        ContentObserver v1 = null;
        Long v0 = arg10 == 2 ? Long.valueOf(Long.parseLong(k.b(arg9))) : null;
        Uri[] v5 = k.b;
        int v3;
        for (v3 = 0; v3 <= 0; ++v3) {
            Uri v2 = v5[0];
            if (v0 != null) {
                v2 = ContentUris.withAppendedId(v2, v0.longValue());
            }

            this.h.getContentResolver().notifyChange(v2, v1);
        }
    }

    private static final void a(String arg1, ContentValues arg2, ContentValues arg3) {
        Integer v0 = arg2.getAsInteger(arg1);
        if (v0 != null) {
            arg3.put(arg1, v0);
        }
    }

    private static final void a(String arg1, ContentValues arg2, ContentValues arg3, String arg4) {
        k.c(arg1, arg2, arg3);
        if (!arg3.containsKey(arg1)) {
            arg3.put(arg1, arg4);
        }
    }

    private static void a(String[] arg4, String arg5, String[] arg6, String arg7, SQLiteDatabase arg8) {
        int v1 = 0;
        StringBuilder v2 = new StringBuilder();
        v2.append("starting query, database is ");
        if (arg8 != null) {
            v2.append("not ");
        }

        v2.append("null; ");
        if (arg4 == null) {
            v2.append("projection is null; ");
        } else if (arg4.length == 0) {
            v2.append("projection is empty; ");
        } else {
            int v0;
            for (v0 = 0; v0 < arg4.length; ++v0) {
                v2.append("projection[");
                v2.append(v0);
                v2.append("] is ");
                v2.append(arg4[v0]);
                v2.append("; ");
            }
        }

        v2.append("selection is ");
        v2.append(arg5);
        v2.append("; ");
        if (arg6 == null) {
            v2.append("selectionArgs is null; ");
        } else {
            if (arg6.length == 0) {
                v2.append("selectionArgs is empty; ");
            } else {
                while (v1 < arg6.length) {
                    v2.append("selectionArgs[");
                    v2.append(v1);
                    v2.append("] is ");
                    v2.append(arg6[v1]);
                    v2.append("; ");
                    ++v1;
                }
            }
        }

        v2.append("sort is ");
        v2.append(arg7);
        v2.append(".");
        Log.v("SsDownloadManager", v2.toString());
    }

    private static String b(Uri arg2) {
        return arg2.getPathSegments().get(1);
    }

    private static final void b(String arg1, ContentValues arg2, ContentValues arg3) {
        Boolean v0 = arg2.getAsBoolean(arg1);
        if (v0 != null) {
            arg3.put(arg1, v0);
        }
    }

    private static final void c(String arg1, ContentValues arg2, ContentValues arg3) {
        String v0 = arg2.getAsString(arg1);
        if (v0 != null) {
            arg3.put(arg1, v0);
        }
    }
}

